// pages/user/user.js
const app = getApp();

Page({
  data: {
    user: null,
    loading: false,
    level: null,
    checkIn: false,
    needRefresh: false,
    showAchievementModal: false,
    achievements: []
  },

  onLoad() {},

  onShow() {
    // 如果是首次进入或标记了需要刷新，则刷新数据
    if (!this.data.user || this.data.needRefresh) {
      this.setData({ loading: true, needRefresh: false });
      // 如果是从profile返回（needRefresh为true），延迟500ms确保后端完成更新
      const delay = this.data.needRefresh ? 500 : 0;
      setTimeout(() => {
        this.fetchMe();
      }, delay);
    }
  },

  onPullDownRefresh() {
    this.fetchMe(true);
  },

  // 跳转到个人资料页面
  onNavigateToProfile() {
    // 标记需要刷新，从profile返回时会刷新数据
    this.setData({ needRefresh: true });
    wx.navigateTo({
      url: '/pages/user/profile/profile'
    });
  },

  // 跳转到意见反馈页面
  onNavigateToFeedback() {
    wx.navigateTo({
      url: '/pages/user/feedback/feedback'
    });
  },

  // 退出登录
  onLogout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('token');
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }
      }
    });
  },

  async fetchMe(fromPullDown = false) {
    const token = wx.getStorageSync('token')
    if (!token) {
      return;
    }
    if (!fromPullDown) this.setData({ loading: true })
    try {
      const res = await app.request({ url: '/api/auth/me', method: 'GET' })
      if (res.statusCode === 200 && res.data) {
        // 支持两种结构：{ success, data: { user, level } } 或 { success, data: user }
        const payload = res.data.data || null
        const user = payload && payload.user ? payload.user : payload
        const level = payload && payload.level ? payload.level : null
        const checkIn = !!(payload && typeof payload.check_in !== 'undefined' ? payload.check_in : false)
        const levelProgress = 0
        const levelProgressWidth = `${levelProgress}%`
        this.setData({ user: user || null, level, checkIn })
      }
    } finally {
      if (fromPullDown) wx.stopPullDownRefresh()
      this.setData({ loading: false })
    }
  },
  
  // 静默更新用户数据，不显示loading状态
  async fetchMeSilently() {
    const token = wx.getStorageSync('token')
    if (!token) {
      return;
    }
    try {
      const res = await app.request({ url: '/api/auth/me', method: 'GET' })
      if (res.statusCode === 200 && res.data) {
        // 支持两种结构：{ success, data: { user, level } } 或 { success, data: user }
        const payload = res.data.data || null
        const user = payload && payload.user ? payload.user : payload
        const level = payload && payload.level ? payload.level : null
        // 不更新checkIn状态，因为已经在onCheckin中提前设置了
        const levelProgress = 0
        const levelProgressWidth = `${levelProgress}%`
        this.setData({ user: user || null, level })
      }
    } catch (e) {
      // 静默处理错误，不影响用户体验
      console.error('静默更新用户数据失败', e)
    }
  },

  // 防止冒泡
  preventBubble() {
    return;
  },

  // 显示成就弹窗
  async onShowAchievement() {
    this.setData({ showAchievementModal: true });
    
    // 获取成就数据
    try {
      const res = await app.request({ url: '/api/achievement', method: 'GET' });
      if (res.statusCode === 200 && res.data && res.data.success) {
        this.setData({ achievements: res.data.data || [] });
      }
    } catch (e) {
      console.error('获取成就数据失败', e);
      wx.showToast({ title: '获取成就数据失败', icon: 'none' });
    }
  },

  // 关闭成就弹窗
  onCloseAchievement() {
    this.setData({ showAchievementModal: false });
  },

  async onCheckin() {
    if (this.data.checkIn) return;
    
    // 立即更新UI状态，实现无感刷新
    this.setData({ checkIn: true });
    
    try {
      // 后台发送请求
      const res = await app.request({ url: '/api/auth/checkIn', method: 'POST' });
      
      if (res.statusCode === 200 && res.data && (res.data.success || res.data.code === 200)) {
        // 签到成功，静默更新用户数据
        this.fetchMeSilently();
        
        // 显示轻量级提示
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 1500
        });
      } else {
        // 签到失败，恢复UI状态
        this.setData({ checkIn: false });
        wx.showToast({ title: res.data?.message || '签到失败', icon: 'none' });
      }
    } catch (e) {
      // 网络错误，恢复UI状态
      this.setData({ checkIn: false });
      wx.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  }
})